package org.moon.framework.autoconfigure.sms.impl;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.github.qcloudsms.SmsMultiSender;
import com.github.qcloudsms.SmsMultiSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import com.google.common.collect.Lists;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.sms.SmsManager;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.moon.framework.autoconfigure.sms.SmsService;
import org.moon.framework.autoconfigure.sms.domain.SmsResponse;
import org.moon.framework.autoconfigure.sms.props.SmsProperties;
import org.moon.framework.autoconfigure.utils.Func;
import org.springframework.http.HttpStatus;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 七牛云短信发送类
 * @author ninglong
 */
@Slf4j
public class QiniuSmsProviderImpl implements SmsService,SmsProvider {

    private SmsManager smsManager = null;
    private SmsProperties smsProperties = null;

    @Override
    public SmsService builder(SmsProperties smsProperties){
        this.smsProperties = smsProperties;
        Auth auth = Auth.create(smsProperties.getAccessKey(), smsProperties.getSecretKey());
        smsManager = new SmsManager(auth);
        return this;
    }

    @Override
    public SmsResponse sendSingleSms(String mobile, String templateCode, Map<String, String> templateParams) {
        List<String> mobiles = Lists.newArrayList();
        mobiles.add(mobile);
        return sendMultiSms( mobiles, templateCode, templateParams);
    }

    @Override
    public SmsResponse sendMultiSms(List<String> mobiles, String templateCode, Map<String, String> templateParams) {
        try {
            Response response = smsManager.sendMessage(templateCode, Func.toStrArray(String.join(Func.COMMA, mobiles)), templateParams);
            return new SmsResponse(response.isOK(), response.statusCode, response.toString());
        } catch (QiniuException e) {
            e.printStackTrace();
            return new SmsResponse(Boolean.FALSE, HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
        }
    }
}
